package wxpay

import (
	"bytes"
	"encoding/xml"
	"io/ioutil"
	"net/http"
	"strings"

	uuid "github.com/satori/go.uuid"
)

type RefundQueryReq struct {
	AppId      string `xml:"appid"`
	MchId      string `xml:"mch_id"`
	NonceStr   string `xml:"nonce_str"`
	OutTradeNo string `xml:"out_trade_no"`
	Sign       string `xml:"sign"`
}

func WxRefundQuery(appId string, orderCode string) (WxPayResponse, error) {
	var refundQueryReq RefundQueryReq
	refundQueryReq.AppId = appId
	refundQueryReq.MchId = MchId
	sourceUuid := uuid.NewV4()
	formatUuid := strings.Replace(sourceUuid.String(), "-", "", -1)
	refundQueryReq.NonceStr = formatUuid
	refundQueryReq.OutTradeNo = orderCode

	var mReqMap map[string]interface{}
	mReqMap = make(map[string]interface{}, 0)
	mReqMap["appid"] = refundQueryReq.AppId
	mReqMap["mch_id"] = refundQueryReq.MchId
	mReqMap["nonceStr"] = refundQueryReq.NonceStr
	mReqMap["out_trade_no"] = refundQueryReq.OutTradeNo
	refundQueryReq.Sign = WxPayCalcSign(mReqMap, MchSecret)

	xmlReq, err := xml.Marshal(refundQueryReq)
	if err != nil {
		return WxPayResponse{}, err
	}
	strReq := string(xmlReq)
	strReq = strings.Replace(strReq, "RefundQueryReq", "xml", -1)
	xmlReq = []byte(strReq)

	request, err := http.NewRequest("POST", "https://api.mch.weixin.qq.com/pay/refundquery", bytes.NewReader(xmlReq))
	if err != nil {
		return WxPayResponse{}, err
	}
	request.Header.Set("Accept", "application/xml")
	request.Header.Set("Content-Type", "application/xml;charset=utf-8")

	httpClient := http.Client{}
	response, err := httpClient.Do(request)
	if err != nil {
		return WxPayResponse{}, err
	}

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return WxPayResponse{}, err
	}

	var payResponse WxPayResponse
	err = xml.Unmarshal(responseBody, &payResponse)
	if err != nil {
		return WxPayResponse{}, err
	}

	return payResponse, nil
}
